package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.system.domain.AlarmType;
import com.ruoyi.system.service.IAlarmTypeService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.UserAlarmTypeMapper;
import com.ruoyi.system.domain.UserAlarmType;
import com.ruoyi.system.service.IUserAlarmTypeService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;

/**
 * 用户告警关系表Service业务层处理
 * 
 * @author wp
 * @date 2023-08-10
 */
@Service
public class UserAlarmTypeServiceImpl extends ServiceImpl<UserAlarmTypeMapper, UserAlarmType> implements IUserAlarmTypeService {
    @Autowired
    private UserAlarmTypeMapper userAlarmTypeMapper;
    @Autowired
    private IAlarmTypeService alarmTypeService;

    @Override
    public List<UserAlarmType> selectList(UserAlarmType userAlarmType) {
        return userAlarmTypeMapper.list(userAlarmType);
    }

    @Transactional
    @Override
    public void updateAlarmType(Integer[] alarmTypes){
        Long userId = getUserId();
        //移除原先的报警类型
        userAlarmTypeMapper.delete(new QueryWrapper<UserAlarmType>().eq("user_id", userId));
        if (ObjectUtils.isEmpty(alarmTypes)) return;
        List<UserAlarmType> resultList = Arrays.stream(alarmTypes).map(i -> new UserAlarmType()
                .setUserId(userId)
                .setAlarmType(i)).collect(Collectors.toList());
        //批量新增报警类型
        saveBatch(resultList);
    }

    @Transactional
    @Override
    public int removeByTypeIds(Long[] typeIds){
        return userAlarmTypeMapper.removeByTypeIds(typeIds);
    }

    @Transactional
    @Override
    public List<JSONObjectPro> getUserAlarmTypes(){
        Map<Integer, AlarmType> userAlarmTypeMap = alarmTypeService.getUserAlarmTypeMap();
        List<JSONObjectPro> resultList = selectList(new UserAlarmType().setUserId(getUserId()))
                .stream().map(item -> new JSONObjectPro()
                        .put("id", item.getAlarmType())
                        .put("name", userAlarmTypeMap.get(item.getAlarmType()) == null ? "" : userAlarmTypeMap.get(item.getAlarmType()).getName())).collect(Collectors.toList());
        return resultList;
    }
}
